#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import requests
import click
import os
import shutil
from lxml import html
from retrying import retry
from tqdm import tqdm

PROXY_URI = 'http://127.0.0.1:7890'
CENSORED_PATH = "D:/AV/Av_Cartoon/Censored"
UNCENSORED_PATH = "D:/AV/Av_Cartoon/Uncensored"
TOP_URL = "https://www.javbus.com"


def get_type_pic(proxy_uri: str, fanhao: str, parent_path: str, multi: bool):
    url = 'https://www.javbus.com/' + fanhao
    proxies = {'http': proxy_uri, 'https': proxy_uri}
    r = requests.get(url, proxies=proxies)
    if r.status_code == 200:
        # print(r.text)
        tree = html.fromstring(r.text)
        av_type = tree.xpath('//li[@class="active"]/a/text()')[0]
        # print(xx)
        img_url = tree.xpath('//a[@class="bigImage"]/img/@src')[0]
        print(img_url)
        # print(xx2)
        thumb_url = img_url.replace("/cover/", "/thumb/")
        thumb_url = thumb_url.replace("_b.jpg", ".jpg")
        thumb_url = thumb_url.replace("pl.jpg", "ps.jpg")
        # print(xx3)
        if multi:
            download_file(proxy_uri, img_url, os.path.join(parent_path, "cover.jpg"))
            download_file(proxy_uri, thumb_url, os.path.join(parent_path, "cover-thumb.jpg"))
        else:
            download_file(proxy_uri, img_url, os.path.join(parent_path, fanhao + ".jpg"))
            download_file(proxy_uri, thumb_url, os.path.join(parent_path, fanhao + "-thumb.jpg"))
        return av_type, img_url, thumb_url
    else:
        tqdm.write("找不到番号 " + fanhao)
        return None, None, None


@retry
def download_file(proxy_uri: str, url: str, name: str):
    """
    从url下载文件，并命名为name
    :param proxy_uri: 代理连接地址
    :param url: 下载目标URL
    :param name: 保存文件路径
    :return: None
    """
    proxies = {'http': proxy_uri, 'https': proxy_uri}
    with requests.get(url=TOP_URL+url, stream=True, proxies=proxies) as resp:
        if resp.status_code == 200:
            # stream=True的作用是仅让响应头被下载，连接保持打开状态
            with open(name, "wb") as f:
                for data in resp.iter_content(1024):
                    f.write(data)
                print(name + " downloaded.")


@click.command()
@click.option("--proxy_uri", "-p", help="Socks5连接地址", required=True, type=str, default=PROXY_URI, show_default=True)
@click.option("--censored_path", "-c", help="骑兵目标路径", required=True, type=click.Path(exists=True),
              default=CENSORED_PATH, show_default=True)
@click.option("--uncensored_path", "-u", help="步兵目标路径", required=True, type=click.Path(exists=True),
              default=UNCENSORED_PATH, show_default=True)
@click.argument("target_path", type=click.Path(exists=True))
def sougua_path(proxy_uri: str, censored_path: str, uncensored_path: str, target_path: str):
    none_list = {"Censored", "Uncensored"}
    type_ht = {}
    none_count = 0
    print("生成AV目录结构")
    for lst in os.listdir(target_path):
        target_lst = os.path.join(target_path, lst)
        if os.path.isfile(target_lst):
            if lst.endswith(("mkv", "mp4", "wmv", "rmvb", "avi", "rm", "jpg", "png")):
                fanhao = lst[:lst.rindex(".")]
                if fanhao.endswith(("A", "B", "C", "D", "E")):
                    fanhao = fanhao[:-1]
                if not os.path.exists(os.path.join(target_path, fanhao)):
                    os.mkdir(os.path.join(target_path, fanhao))
                shutil.move(target_lst, os.path.join(target_path, fanhao))

    print("对所有AV目录进行搜刮...")
    for lst in tqdm(os.listdir(target_path), desc="file"):
        target_lst = os.path.join(target_path, lst)
        if os.path.isdir(target_lst):
            if lst not in none_list:
                multi = check_multi(target_lst)
                av_type, img_url, thumb_url = get_type_pic(proxy_uri, lst, target_lst, multi)
                if av_type is not None:
                    if av_type in type_ht:
                        type_ht[av_type] += 1
                    else:
                        type_ht[av_type] = 1
                    if av_type == "有碼":
                        shutil.move(target_lst, censored_path)
                    elif av_type == "無碼":
                        shutil.move(target_lst, uncensored_path)
                    tqdm.write(img_url)
                else:
                    none_count += 1

    print(type_ht)
    print("找不到番号%d个" % none_count)


def check_multi(target_path: str):
    count = 0
    for lst in target_path:
        if os.path.isfile(lst):
            if lst.endswith(("mkv", "mp4", "wmv", "rmvb", "avi", "rm")):
                count += 1
    if count > 1:
        return True
    else:
        return False


if __name__ == '__main__':
    sougua_path()
    # download_file(PROXY_URI, "https://www.javbus.com/pics/cover/84ep_b.jpg", "D:/test123.jpg")
